package com.example.wnn.config.exception;

import cn.hutool.json.JSONUtil;
import com.example.wnn.config.base.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.SimpleDateFormat;

@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public String businessExceptionHandler(BusinessException e){
        log.error("BusinessException：{}",e);
        return getReturnController(ResultVo.error("fail",e.getMessage()));
    }

    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException e){
        log.error("RuntimeException：{}",e);
        return getReturnController(ResultVo.error("fail",e.getMessage()));
    }

    public static String getReturnController(ResultVo result){
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(fmt);
        String reBack = JSONUtil.toJsonStr(result);
        return reBack;
    }
}

